<?php
#use executor

class Compiler {
	public $options;
	public $source;
	public $target;
	
	public $language;
	
	public $output;
	
	public function __construct($source, $target, $language = 'C', $options = '-O2 -std=gnu99 -static -s -lm -x c') {
		$this->options = $options;
		$this->language = $language;
		$this->source = $source;
		$this->target = $target;
	}
	
	public function setLanguage($lang) {
		$this->language = $lang;
	}
	
	public function compile() {
		
		$lang = strtolower($this->language);
		if ($lang == 'c++') $lang = 'cpp';
		$base_command = $lang == 'c' ? 'gcc': 'g++';
		
		$cmd = $base_command . ' ' . $this->options;
		$target = sprintf('-o %s', $this->target);
		$cmd .= ' ' . $target;
		$cmd .= ' ' . $this->source;
		
		if (!file_exists($this->source)) {
			return false;
		}
		
		$exe = new Executor($cmd);
		$exe->setRedirectErrorToOut(true);
		$exe->execute();
		$this->output = stream_get_contents($exe->getOutputStream());
		$exe->join();
		
		if (file_exists($this->target)) {
			return true;
		} else {
			return false;
		}
	}
}
